package net.martinimix.edesk.search;


import com.bluemartini.dna.BMContext;
import com.bluemartini.dna.BMException;
import com.bluemartini.dna.BusinessObject;
import com.bluemartini.dna.BusinessObjectArray;
import com.bluemartini.dna.DNAList;
import com.bluemartini.server.BusinessAction;
import com.bluemartini.util.BasicBusinessObjectUtil;

/**
 * Provides Enterprise Desktop search via Endeca.
 * 
 * @author Scott Rossillo
 *
 */
public class EMSEndecaParametricSearch extends BusinessAction {

	/* (non-Javadoc)
	 * @see com.bluemartini.server.BusinessAction#execute(com.bluemartini.dna.DNAList)
	 */
	public DNAList execute(DNAList dnaIn) throws BMException {
		
		final DNAList config = BMContext.getConfig("pdc.endeca.search.dna");
		final DNAList response = new DNAList();
		final BusinessObject searchInput = dnaIn.getBusinessObject("SEARCH_INPUT");
		final ProductSearch productSearch =
			new ProductSearch(
					config.getString("endecaHost"),
					config.getInteger("endecaPort", 5555), // default ENE port
					config.getString("productIdProperty"));
		
		
		final BusinessObjectArray searchResults = new BusinessObjectArray();
		final BusinessObjectArray productResults;
		
		if(searchInput.getString("searchFor", "").equals("")) {
			throw new BMException("Please enter text to search for!");
		}
		
		productResults =
			productSearch.findProducts(
					searchInput.getString("searchFor", ""),
					searchInput.getInteger("maxRows_cd", 1000));
		
		
		for(int i = 0; i < productResults.size(); i++) {
			searchResults.addElementRef(getObject(productResults.elementAt(i)));
		}
		
		response.setInteger("totalRows", searchResults.size());
		response.setBusinessObjectArrayRef("OBJECT_ARRAY", searchResults);
		
		return response;
	}

	/**
	 * Returns the given object as an "OBJET" business object.
	 */
	private BusinessObject getObject(BusinessObject object) throws BMException {

		BusinessObject genericObject = BMContext.createBusinessObject("OBJECT");
		genericObject.setLongID(object.getLongID());
		genericObject.setInteger("__TYPE", object.getInteger("__TYPE"));
		
		genericObject.setVersion(BasicBusinessObjectUtil.getObjectVersion(object.getLongID()));
		genericObject.setObjectName(object.getObjectName());
		genericObject.setString("shortDesc", object.getString("shortDesc"));
		genericObject.setString("path", object.getString("path"));

		return genericObject;
	}

}
